package com.stylefeng.guns.core.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonUtils {

	/** 日志记录者 */
	protected static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

	/**
	 * JSON转换为Object对象
	 * 
	 * @param json
	 *            JSON字符串
	 * @param clazz
	 *            要转换成的类的类型
	 * @return Object对象
	 */
	public static <T> T jsonToObject(String json, Class<T> clazz) {

		if (StringUtils.isEmpty(json)) {
			return null;
		} else {
			ObjectMapper mapper = new ObjectMapper();
			//objectMapper.configure(DeserializationConfig.FAIL_ON_UNKNOWN_PROPERTIES, false);
			try {
				return mapper.readValue(json, clazz);
			} catch (Exception e) {
				if (logger.isWarnEnabled()) {
					logger.warn("将JSON[" + json + "]转换成[" + clazz.getCanonicalName() + "]出现异常!", e);
				}
				throw new RuntimeException("将JSON[" + json + "]转换成[" + clazz.getCanonicalName() + "]出现异常!");
			}
		}
	}

	/**
	 * Object对象转换为JSON格式 例如List对象、JavaBean对象、JavaBean对象数组、Map对象、List Map对象
	 * 
	 * @param object
	 *            传入的Object对象
	 * @return object的JSON格式字符串
	 */
	public static String toJson(Object object) {

		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.setSerializationInclusion(Include.NON_NULL);
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			if (logger.isWarnEnabled()) {
				logger.warn("将对象转换成JSON出现异常!", e);
			}
			throw new RuntimeException("将对象转换成JSON出现异常");
		}

	}
}